<?php

namespace IDock\Insurance\YAIC\Response;

use IDock\Http\Response;

class AllYAICResponse extends Response
{
    protected $records = [];

    protected $result = [];

    public function resolve(): Response
    {
        $body = $this->getBody();
        libxml_disable_entity_loader(false);
        $body = simplexml_load_string($body);
        $body = $this->objectToArray($body);
        if ($this->printer and is_string($this->printer)) {
            $this->printer = new $this->printer;
        }

        $responseCode = $body['responseHead']['status'] ?? '';
        $errorMsg = $body['responseHead']['appMessage'] ?? '';

        if ($responseCode !== '0') {
            $this->setError($errorMsg);
            return $this;
        }

        $this->setBody($body ?? []);

        return $this;
    }

    protected function objectToArray($object) {
        if( count($object)==0 )  return trim((string)$object);
        $result = array();
        $object = is_object($object) ? get_object_vars($object) : $object;
        foreach ($object as $key => $val) {
            $val = (is_object($val) || is_array($val)) ? $this->objectToArray($val) : $val;
            $result[$key] = $val;
        }
        return $result;
    }

    public function formatArray($arr): array
    {
        if (empty($arr)) return [];
        if (!is_array($arr)) {
            return [];
        }
        if (!isset($arr[0])) {
            $tmp = $arr;
            unset($arr);
            $arr[] = $tmp;
        }
        return $arr;
    }
}
